package com.sky.aop;

import com.sky.annotation.AutoFillInsert;
import com.sky.annotation.AutoFillUpdate;
import com.sky.context.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @projectName: HF62sky
 * @package: com.sky.aop
 * @className: AutoFillAop
 * @author: SunGang
 * @description: TODO
 * @date: 2023/12/5 9:37
 * @version: 1.0
 */
@Aspect
@Component
@Slf4j
public class AutoFillAop {
    @Pointcut("@annotation(com.sky.annotation.AutoFillInsert)||@annotation(com.sky.annotation.AutoFillUpdate)")
    public void pt(){}

    @Before("pt()")
    public void AutoFill(JoinPoint joinPoint){
        Signature signature = joinPoint.getSignature();
        MethodSignature signature2 = (MethodSignature) signature;
        Method method = signature2.getMethod();
        AutoFillInsert annotation= method.getAnnotation(AutoFillInsert.class);
        AutoFillUpdate annotation2 = method.getAnnotation(AutoFillUpdate.class);
        try {
            Object[] args = joinPoint.getArgs();
            Object param = args[0];
            Class<?> clazz = param.getClass();
            Method setUpdateTime = clazz.getMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = clazz.getMethod("setUpdateUser", Long.class);
            setUpdateTime.invoke(param,LocalDateTime.now());
            setUpdateUser.invoke(param,BaseContext.getCurrentId());
            if(Objects.nonNull(annotation)){
                Method setCreateTime = clazz.getMethod("setCreateTime", LocalDateTime.class);
                Method setCreateUser = clazz.getMethod("setCreateUser", Long.class);
                setCreateUser.invoke(param,BaseContext.getCurrentId());
                setCreateTime.invoke(param,LocalDateTime.now());
            }

        } catch (Exception e) {
           log.info("-------------自动注入数据失败----------------",e);
        }
    }
}
